import LogFactory from "log/LogFactory";
// import UserLoginDataStorage from "storage/UserLoginDataStorage";
import JsonResult from "http/JsonResult";
import { LoginData, LoginSuccessData } from "type/LoginSuccessData";
import {getStringFromLocalStore} from "../storage/LocalStorageUtill";

const Authorization: string = "Authorization";
const log = LogFactory.getLogger("RequestHandler");
export default class RequestHandler {
    private static BASE_URL: string = "http://192.168.2.199:9527";
    // private static BASE_URL: string = "http://localhost:9527";
    /** RequestHandler GET 请求方法 */
    public static async get<T>(url: string): Promise<JsonResult<T>> {
        // log.request.ts("GET请求", url);
        return await fetch(this.BASE_URL + url, {
            method: "GET",
            headers: this.getHeaders()
        }).then(this.responseConvert)
            .catch(this.errorConvert);
    }
    /** RequestHandler POST 请求方法 */
    public static async post<T>(url: string, data: object): Promise<JsonResult<T>> {
        // log.request.ts("GET请求", url);
        return await fetch(this.BASE_URL + url, {
            method: "POST",
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        }).then(this.responseConvert)
            .catch(this.errorConvert);
    }
    /** 
     * RequestHandler PUT 请求方法(添加新数据的时候使用)
     * @param url 请求地址
     * @param data 请求数据
     * */
    public static async put<T>(url: string, data: object): Promise<JsonResult<T>> {
        // log.request.ts("GET请求", url);
        return await fetch(this.BASE_URL + url, {
            method: "PUT",
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        }).then(this.responseConvert)
            .catch(this.errorConvert);
    }
    /** RequestHandler DELETE 请求方法 */
    public static async delete<T>(url: string, data?: object | []): Promise<JsonResult<T>> {
        // log.request.ts("GET请求", url);
        return await fetch(this.BASE_URL + url, {
            method: "DELETE",
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        }).then(this.responseConvert)
            .catch(this.errorConvert);
    }
    /** 用户登录专用方法 */
    public static async login(data: LoginData): Promise<JsonResult<LoginSuccessData>> {
        return await fetch(this.BASE_URL + "/login", {
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
            body: `username=${data.username}&password=${data.password}`
        })
            .then(res => res.json())
            .catch(err => {
                log.error("请求错误", err);
                return Promise.reject(err);
            });
    }

    static errorConvert(error: any) {
        log.error("请求错误", error);
        // return Promise.reject(error);
        // throw new Error("Method not implemented.");
    }

    static responseConvert(response: Response) {
        // log.request.ts("请求响应的状态码", response.status);
        if(response.status === 417){
            log.request("用户登录过期");
        }
        return response.json();
    }

    static getHeaders() {
        // log.debug("获取请求头",getStringFromLocalStore(Authorization));
        const headers = new Headers();
        headers.set("Content-Type", "application/json");
        headers.set("Accept", "application/json");
        headers.set(Authorization, getStringFromLocalStore(Authorization));
        return headers;
    }

}